package com.mygdx.game;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.SnapshotArray;
import com.badlogic.gdx.utils.TimeUtils;

/**
 * Created by Administrator on 2016/2/22.
 */
public class MonsterGroup extends Group{

    private int monsterNumber;
    private int minY;
    private int maxY;
    private int tempY;
    private TextureAtlas.AtlasRegion region;
    private long nowTime;
    private SnapshotArray<Actor> actors;

    public MonsterGroup(TextureAtlas.AtlasRegion region,int monsterNumber){
        this.region = region;
        this.monsterNumber = monsterNumber;
        minY =0;
        maxY = (int) (MyGame.SCREENHEIGHT - region.getRegionHeight());
        nowTime = TimeUtils.nanoTime();
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        if(TimeUtils.nanoTime()-nowTime>1000000000){
            Array<Actor> monsters = new Array<Actor>();
            nowTime = TimeUtils.nanoTime();
            for(int i=0;i<monsterNumber;i++){
                Image monster = new Image(region);
                boolean isCanAdd = false;
                tempY = MathUtils.random(minY, maxY);
                for(Actor actor:monsters){
                    float yPostion = actor.getY();
                    if((tempY+actor.getHeight())<yPostion||tempY>(yPostion+actor.getHeight())){
                        monster.setPosition(MyGame.SCREENWIDTH - region.getRegionWidth(), tempY);
                        isCanAdd = true;
                    }
                    else{
                        isCanAdd = false;
                        break;
                    }
                }
                if(isCanAdd == true){
                    monsters.add(monster);
                    this.addActor(monster);
                }
                if(i==0){
                    tempY = MathUtils.random(minY, maxY);
                    monster.setPosition(MyGame.SCREENWIDTH - region.getRegionWidth(), tempY);
                    this.addActor(monster);
                    monsters.add(monster);
                }
            }
        }
        actors = this.getChildren();
        for(Actor actor:actors){
            batch.draw(region, actor.getX(), actor.getY());
            actor.setX(actor.getX() - Gdx.graphics.getDeltaTime() * 100);
            if(actor.getX()<0){
                this.removeActor(actor);
            }
        }

    }

}
